package com.cityguardian.threads;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.cityguardian.cityguardianapp.AlertDetailActivity;
import com.cityguardian.cityguardianapp.MapActivity;
import com.cityguardian.ws.ConnectionThread;
import com.google.gson.Gson;

import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class AsyncTaskFollowAcc extends AsyncTask<Integer, Double, String>{

	private AlertDetailActivity activity;
	
	public AsyncTaskFollowAcc(AlertDetailActivity activity){
		this.activity=activity;
	}
	
	@Override
	protected String doInBackground(Integer... arg0) {
		
		String response = registrarFollow();
		return response;
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		if (result == null){
			Log.d("Follow","No se pudo seguir el incidente");
		}else{
			if (result.equals("0")){
				Toast.makeText(activity,
						"Ya se esta siguiendo la alerta", Toast.LENGTH_LONG).show();
				Log.d("Follow","Alerta: "+result);
		    	Intent intent = new Intent(activity, MapActivity.class);	
		    	intent.putExtra("Usuario", activity.usuario);
		    	activity.startActivity(intent);
			}else{
				Toast.makeText(activity,
						"Se esta siguiendo la alerta", Toast.LENGTH_LONG).show();
				Log.d("Follow","Alerta: "+result);
		    	Intent intent = new Intent(activity, MapActivity.class);	
		    	intent.putExtra("Usuario", activity.usuario);
		    	activity.startActivity(intent);
			}
		}    	
	}
	
	private String registrarFollow() {

		List<NameValuePair> param = new ArrayList<NameValuePair>();
		param.add(new BasicNameValuePair("idAlerta", activity.alerta.getIdAlerta()));
		param.add(new BasicNameValuePair("idUsuario", activity.usuario.getIdUsuario()));
		
		String route="/ws/alerta/set_follow_accident/";
		Log.e("log_tag",param.toString());
		
		ConnectionThread connection = new ConnectionThread(param, route);
		String responseBody = connection.getResponse();
		
		if (responseBody==null){
			Log.e("log_tag", "Error in webservice");
			return null;
		}
		Gson gson = new Gson();
	    Log.e("log_tag", responseBody);
		String idAlerta = gson.fromJson(responseBody,String.class);
		return idAlerta;
	}
	
}
